﻿using IOP.SgrA;
using IOP.SgrA.ECS;
using IOP.SgrA.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace VkSample510
{
    public class LightSystem : ComponentSystem
    {
        private Ambient Ambient = new Ambient(0.1f, 0.1f, 0.1f, 0.1f);

        public override void Initialization()
        {
            ContextManager.Foreach<LightGroup>((group) =>
            {
                Context context = ContextManager.GetContext(group.Entity);
                var obj = context.GetContextRenderObject();
                var render = context.GetContextRenderGroup();
                var camera = render.Camera;
                PointLight light = obj.GetComponents<PointLight>().First();
                Span<Vector4> data = stackalloc Vector4[]
                {
                    new Vector4(camera.EyePosition, 1),
                    light.Position,
                    Ambient,
                    light.Strength,
                    light.Strength
                };
                Span<byte> p = MemoryMarshal.AsBytes(data);
                render.PushDataToTexture(p, 0, 0);
            });
        }

        public override void Update(TimeSpan timeSpan)
        {
            if (Input.GetMouseButtonState(MouseButton.ButtonLeft).Action == InputAction.Press)
            {
                var delta = Input.GetMousePositionDelta();
                ContextManager.Foreach<LightGroup>((group) =>
                {
                    Context context = ContextManager.GetContext(group.Entity);
                    var obj = context.GetContextRenderObject();
                    var render = context.GetContextRenderGroup();
                    PointLight light = obj.GetComponents<PointLight>().First();
                    var camera = render.Camera;
                    if (delta.X != 0 || delta.Y != 0)
                    {
                        var old = light.Position;
                        light.ChangePosition(new Vector3(old.X + delta.X * 10.0f / 320, old.Y + delta.Y * 10.0f / 320, old.Z));
                    }
                    Span<Vector4> data = stackalloc Vector4[]
                    {
                        new Vector4(camera.EyePosition, 1),
                        light.Position,
                        Ambient,
                        light.Strength,
                        light.Strength
                    };
                    Span<byte> p = MemoryMarshal.AsBytes(data);
                    render.PushDataToTexture(p, 0, 0);
                });
            }
        }
    }

    public struct LightGroup
    {
        public Entity Entity;
        public LightComponent Light;
    }
}
